package gcosc.fun.hly.fastsso.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import gcosc.fun.hly.fastsso.domain.Bo.PageQuery;
import gcosc.fun.hly.fastsso.domain.SsoRole;
import gcosc.fun.hly.fastsso.domain.SsoRoleUser;
import gcosc.fun.hly.fastsso.domain.SsoUser;
import gcosc.fun.hly.fastsso.mapper.SsoRoleMapper;
import gcosc.fun.hly.fastsso.mapper.SsoRoleUserMapper;
import gcosc.fun.hly.fastsso.result.Code;
import gcosc.fun.hly.fastsso.result.TableDataInfo;
import gcosc.fun.hly.fastsso.service.ISsoRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 角色Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-30
 */
@Service
@RequiredArgsConstructor
public class SsoRoleServiceImpl extends ServiceImpl<SsoRoleMapper, SsoRole> implements ISsoRoleService {

    private final SsoRoleUserMapper ssoRoleUserMapper;

    /**
     * 查询角色
     */
    @Override
    public SsoRole queryById(Long id){
        return baseMapper.selectById(id);
    }

    /**
     * 查询角色列表
     */
    @Override
    public TableDataInfo<SsoRole> queryPageList(SsoRole bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SsoRole> lqw = buildQueryWrapper(bo);
        IPage<SsoRole> result = baseMapper.selectPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询角色列表
     */
    @Override
    public List<SsoRole> queryList(SsoRole bo) {
        LambdaQueryWrapper<SsoRole> lqw = buildQueryWrapper(bo);
        return baseMapper.selectList(lqw);
    }

    private LambdaQueryWrapper<SsoRole> buildQueryWrapper(SsoRole bo) {
        LambdaQueryWrapper<SsoRole> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getRole()), SsoRole::getRole, bo.getRole());
        lqw.eq(StringUtils.isNotBlank(bo.getRealm()), SsoRole::getRealm, bo.getRealm());
        return lqw;
    }

    /**
     * 新增角色
     */
    @Override
    public Boolean insertByBo(SsoRole bo) {
        SsoRole add = BeanUtil.toBean(bo, SsoRole.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改角色
     */
    @Override
    public Boolean updateByBo(SsoRole bo) {
        SsoRole update = BeanUtil.toBean(bo, SsoRole.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SsoRole entity){
        //TODO 做一些数据校验,如唯一约束
        SsoRole one = lambdaQuery().eq(SsoRole::getRealm, entity.getRealm())
                .eq(SsoRole::getRole, entity.getRole()).one();
        if (one != null && entity.getId() == null ||
                entity.getId() != null && !one.getId().equals(entity.getId())){
            Code.BUSINESS_ERR("角色已经存在");
        }
    }

    /**
     * 批量删除角色
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<String> listRoleByUserId(Long id, String realm) {
        List<Long> ids = ssoRoleUserMapper.selectList(Wrappers
                        .<SsoRoleUser>lambdaQuery()
                        .eq(SsoRoleUser::getUserId, id))
                .stream().map(n -> n.getRoleId())
                .collect(Collectors.toList());

        if (ids.size() == 0){
            return new ArrayList<>();
        }

        return listByIds(ids).stream().map(n ->
                n.getRole()).collect(Collectors.toList());
    }

    @Override
    public void editRoleUser(Long id, String realm, List<String> roles) {
        ssoRoleUserMapper.delete(Wrappers
                .<SsoRoleUser>lambdaQuery()
                .eq(SsoRoleUser::getUserId, id));

        if (roles.size() == 0){
            return;
        }

        List<SsoRole> list = lambdaQuery().eq(SsoRole::getRealm, realm)
                .in(SsoRole::getRole, roles)
                .select(SsoRole::getId)
                .list();

        for (SsoRole ssoRole : list) {
            ssoRoleUserMapper
            .insert(SsoRoleUser
                .builder()
                .roleId(ssoRole.getId())
                .userId(id)
                .build());
        }

    }
}
